import os

from flask import Flask
from app.ext import register_ext, db
from pathlib import Path


def create_app():
    BASE_DIR = Path(__file__).parent.parent

    app = Flask(__name__)


    app.template_folder = '../templates'
    app.static_folder = '../static'
    # 设置SQLALCHEMY_DATABASE_URI
    app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///' + os.path.join(BASE_DIR, 'pdm_info.db')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=True
    app.config['SECRET_KEY']='your-secret-key-here'
    register_ext(app)


    from app.route import app_bp
    app.register_blueprint(app_bp)

    with app.app_context():
        db.create_all()
        # 初始化角色
        from app.models import User

        admin_user = User.query.filter_by(username='admin').first()
        if not admin_user:
            admin_user = User(username='admin')
            admin_user.set_password('admin123')  # 设置初始密码
            admin_user.is_admin = True
            admin_user.is_active = True
            admin_user.email = 'admin@example.com'
            db.session.add(admin_user)
            db.session.commit()

            print("Successfully created admin user")
            user_user = User(username='18859633382')
            user_user.set_password('123456')  # 设置初始密码
            user_user.is_admin = True
            user_user.is_active = True
            user_user.email = 'l18859633382@163.com'
            db.session.add(user_user)
            db.session.commit()
            print("Successfully created 18859633382")
            user_user = User(username='15779870664')
            user_user.set_password('123456')  # 设置初始密码
            user_user.is_admin = True
            user_user.is_active = True
            user_user.email = '15779870664@163.com'
            db.session.add(user_user)
            db.session.commit()
            print("Successfully created 15779870664")


        """初始化"""
        from app.utils.PDMHandler import PDMHandler

        pdm_handler = PDMHandler()
        pdm_handler.import_all_to_db()


    return app
